<template>
  <div>
    <el-breadcrumb separator="/" class="submenu">
      <el-breadcrumb-item class="submenu-left">开发申请新增</el-breadcrumb-item>
    </el-breadcrumb>    
    <el-container>
      <div class="el_submit">
        <el-button type="primary" icon="el-icon-time" @click="saveForm('form',tableData)">暂存</el-button>
        <el-button type="success" icon="el-icon-success" @click="saveAndSubmit('form',tableData)">提交</el-button>
      </div>
      <el-header class="el_header" style="padding:20px;height:auto;">
        <el-form :inline="true" :model="form" class="add-form" label-width="100px" ref="form" :rules="rules">
            <el-input style="display:none" v-model="form.id"></el-input>
            <el-input style="display:none" v-model="form.dlvApplyItemJsonStr"></el-input>
            <el-form-item label="采购组织:" prop="purOrgId">
              <el-select v-model="form.purOrgId" placeholder="请选择" @change="handleChange">
                <el-option v-for="item in purOrgOptions" :key="item.id" :label="item.purOrgName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="采购组:" prop="purGroupId">
              <el-select v-model="form.purGroupId" placeholder="请选择">
                <el-option v-for="item in relationPurGroup" :key="item.id" :label="item.purGroupName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="品类:" prop="categoryName">
              <select-tree :multiple="false" ref="selectTree" v-model="form.categoryName"></select-tree>
            </el-form-item>
            <el-form-item label="申请主题:" prop="title">
              <el-input v-model="form.title" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="申请原因:" class="upload" prop="applyReason">
              <el-input type="textarea" v-model="form.applyReason" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="现有供应商:" class="upload" prop="vendors">
              <el-input type="textarea" v-model="form.vendors" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="附件上传：" class="upload">
              <el-upload
                class="upload-file"
                ref="upload"
                :action="this.lib.config.host.system + '/common/fileupload/upload'"
                :data=fileData
                :limit="1"
                :on-success="uploadSuccess"         
                :file-list="fileList">
                <el-button slot="trigger" type="primary">选取文件</el-button>
              </el-upload>
            </el-form-item>
        </el-form>
      </el-header>
      <div class="el_submit">
        <el-button type="primary" icon="el-icon-plus" @click="dialogFormVisible = true">新增</el-button>
      </div>
      <div>
        <el-table border :data="tableData" :default-sort="{prop: 'vendorCode', order: 'descending'}">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="id" v-if='isShow'></el-table-column>
          <el-table-column prop="operation" align="center" :width="70" label="操作">
            <template slot-scope="scope">
              <el-button type="text" @click="delDlvVendorRow(index)">删除</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="vendorCode" align="center" :width="150" label="供应商编码"></el-table-column>
          <el-table-column prop="vendorName" align="center" :width="200" label="供应商名称"></el-table-column>
          <el-table-column prop="vendorLevel" align="center" :width="150" :formatter="vendorLevelFormatter" label="供应商等级"></el-table-column>
          <el-table-column prop="applyType" align="center" :width="200" :formatter="applyTypeFormatter" label="引入类型"></el-table-column>
          <el-table-column prop="dlvItemFlow" align="center" :width="400" :formatter="dlvItemFlowFormatter" label="开发流程"></el-table-column>
          <el-table-column prop="supplyArea" align="center" :width="300" :formatter="supplyAreaFormatter" label="供货区域"></el-table-column>
          <el-table-column prop="remarks" align="center" :width="300" label="备注"></el-table-column>
        </el-table>
      </div>
    </el-container>
    <!-- 新增开发供应商明细 -->
    <div>
      <el-dialog title="新增供应商" :visible.sync="dialogFormVisible">
        <el-form :model="addDlvVendorForm">
          <el-row>
            <el-col :span="10">
              <el-form-item label="引入类型" :label-width="formLabelWidth">
                <el-select v-model="addDlvVendorForm.applyType" placeholder="请选择" @change="applyTypeChange">
                  <el-option v-for="item in applyTypeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="供应商" :label-width="formLabelWidth">
                <select-table v-model="addDlvVendorForm.vendorName" @on-selection-data="getRowData" :vendorLevel="vendorLevel"></select-table>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="供应商编码" :label-width="formLabelWidth">
                <el-input v-model="addDlvVendorForm.vendorCode" readonly="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="供应商等级" :label-width="formLabelWidth">
                <el-input v-model="addDlvVendorForm.vendorLevel" readonly="true"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="开发流程" :label-width="formLabelWidth">
            <template>
              <el-checkbox-group v-model="dlvItemFlows">
                <el-checkbox v-for="item in dlvFlowOptions" :label="item.id" :key="item.id">{{item.remarks}}</el-checkbox>
              </el-checkbox-group>
            </template>
          </el-form-item>
          <el-form-item label="供货区域" :label-width="formLabelWidth">
            <el-select v-model="supplyAreas" multiple placeholder="请选择">
              <el-option v-for="item in supplyAreaOptions" :key="item.id" :label="item.purOrgName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注" :label-width="formLabelWidth">
            <el-input type="textarea" v-model="addDlvVendorForm.remarks" auto-complete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="insertRow(addDlvVendorForm,dlvItemFlows,supplyAreas)">确定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
  import SelectTable from '@/components/common/select-ext/select-table';
  import SelectTree from '@/components/common/select-ext/select-tree.vue';
  export default {
    components: {
      SelectTable,
      SelectTree
    },
    data() {
      var validatePurOrg = (rule, value, callback) => {
        if (!!!value) {
          callback(new Error('请选择采购组织！'));
        }
         callback();
      };
      var validatePurGroup = (rule, value, callback) => {
        if (!!!value) {
          callback(new Error('请选择采购组！'));
        }
         callback();
      };
      var validateCategory = (rule, value, callback) => {
        if (!!!value) {
          callback(new Error('请选择品类！'));
        }
         callback();
      };
      var validateTitle = (rule, value, callback) => {
        if (!!!value) {
          callback(new Error('请输入标题！'));
        } else if (value.length > 50) {
          callback(new Error('请输入小于50位的标题！'));
        }
         callback();
      };
      var validateApplyReason = (rule, value, callback) => {
        if (!!!value) {
          callback(new Error('请输入申请原因！'));
        } else if (value.length > 20) {
          callback(new Error('长度请限制在500个字内！'));
        }
         callback();
      };
      var validateVendors = (rule, value, callback) => {
        if (!!!value) {
          callback(new Error('请输入现有供应商！'));
        } else if (value.length > 500) {
          callback(new Error('长度请限制在500个字内！'));
        }
         callback();
      };
      return {
         rules: {
          title: [
            {required: true, validator: validateTitle, trigger: 'blur' }
          ],
          purOrgId: [
            {required: true, validator: validatePurOrg, trigger: 'change' }
          ],
          purGroupId: [
            {required: true, validator: validatePurGroup, trigger: 'change' }
          ],
          applyReason: [
            {required: true, validator: validateApplyReason, trigger: 'blur' }
          ],
          vendors: [
            {required: true, validator: validateVendors, trigger: 'blur' }
          ],
          categoryName:[
            {required: true, validator: validateCategory, trigger: 'change' }
          ]
        },
        // 对话框列宽
        formLabelWidth: '120px',
        // 附件上传集合
        fileList: [],
        // 定义附件的业务模块和业务动作
        fileData: {
          busAction: "APPLY",
          tableName: "VD_DLV_APPLY"
        },
        // 是否显示隐藏列
        isShow: false,
        // 对话框显示、隐藏属性
        dialogFormVisible: false,
        form: {
          id: '',
          purOrgId: '',
          dlvApplyItemJsonStr: '',
          attFileUrl: '',
          attFileName: ''
        },
        // 新增供应商表单
        addDlvVendorForm: {
          vendorCode: '',
          vendorLevel: ''
        },
        purOrgOptions:[],
        relationPurGroup: [],
        // 引入类型
        applyTypeOptions: [{
            value: '1',
            label: '新供应商'
          },
          {
            value: '2',
            label: '合格供应商-新物料开发'
          }
        ],
        vendorLevel:null,
        // 供货区域选项
        supplyAreaOptions: [],
        // 开发流程选项
        dlvFlowOptions: [],
        // 初始化表格数据
        tableData: [],
        // 新增时，选中的开发流程
        dlvItemFlows: [],
        // 新增时，选中的供货区域
        supplyAreas: []
      };
    },
    mounted() {
      this.initData();
      // null为新增不查询
      if(this.$route.query.dlvApplyId != null){
        this.getDlvApply();
        this.getDlvApplyItem();
     }
    },
    // 监听品类下拉
    watch: {
      'form.categoryName':function(val){
         let data = this.$refs['selectTree'].getResultData();
         if(!!data.categoryCode){
           this.form.categoryCode = data.categoryCode;
         }
      }
    },
    methods: {
      initData(){
        // 获取采购组织
        this.getSelectData('get', this.lib.config.host.masterData + '/system/purOrgMgt/purOrg/getPurOrgByUserId/' + this.getCurrUserId(), {}, 'id', 'purOrgName').then((data)=>{
          this.purOrgOptions = data;
        });
        // 查询供货区域数据字典
        this.getSelectData('get', this.lib.config.host.masterData + '/system/purOrgMgt/purOrg/getAllApplyFactory', {}, 'id', 'purOrgName').then((data)=>{
          this.supplyAreaOptions = data;
        });
        // 查询开发流程数据字典
        this.getDicData('DLV_FLOW').then((data)=>{
          this.dlvFlowOptions = data;
        });
      },
      // 采购组织在改变的时候查询采购组
      handleChange(value) {
        // 获取srm采购组
        this.getSelectData('post', this.lib.config.host.masterData + '/mdata/purOrgMgt/purGroup/getByPurOrgId/' + value, {}, 'id', 'purGroupName').then((data)=>{
          this.relationPurGroup = data;
        });
      },   
      // 查询供应商开发申请
      getDlvApply() {
        this.axios.post(this.lib.config.host.vendorDlv + "/vendormgt/dlv/dlvApply/findDlvApply/" + this.$route.query.dlvApplyId)
          .then((response) => {
            this.form = response.data;
            this.handleChange(this.form.purOrgId);
            this.fileList.push({
              url: response.data.attFileUrl,
              name: response.data.attFileName
            })
          })
          .catch((error) => {
            console.log(error);
          });
      }, 
      // 查询供应商开发申请明细
      getDlvApplyItem() {
        this.axios.post(this.lib.config.host.vendorDlv + "/vendormgt/dlv/dlvApply/findDlvApplyItemList/" + this.$route.query.dlvApplyId)
          .then((response) => {
            this.tableData = response.data;
          })
          .catch((error) => {
            console.log(error);
          });
      },
      // 引入类型变化
      applyTypeChange(val){
        if(val == 2){
          this.vendorLevel = 3
        } else {
          this.vendorLevel = 2
        }
      },
      // 双击供应商触发
      getRowData(data){
        this.addDlvVendorForm.vendorLevel = data.vendorLevel;
        this.addDlvVendorForm.vendorCode = data.vendorCode;
      },
      // 新增开发申请明细数据
      insertRow(addDlvVendorForm, dlvItemFlows, supplyAreas) {
        this.dlvItemFlows = dlvItemFlows.sort(function(a,b){ // 开发流程数组排序，防止数组按照选择的先后顺序排列
          if (a > b) {
            return 1;
          } else if (a < b){
            return -1
          } else {
            return 0;
          }    
        })
        this.addDlvVendorForm.dlvItemFlow = dlvItemFlows.join(',');
        this.addDlvVendorForm.supplyArea = supplyAreas.join(',');
        this.tableData.push({
            applyType: addDlvVendorForm.applyType,
            vendorCode: addDlvVendorForm.vendorCode,
            vendorName: addDlvVendorForm.vendorName,
            vendorLevel: addDlvVendorForm.vendorLevel,
            dlvItemFlow: addDlvVendorForm.dlvItemFlow,
            supplyArea: addDlvVendorForm.supplyArea,
            remarks: addDlvVendorForm.remarks
          }),
          // 对话框显示、隐藏属性
          this.dialogFormVisible = false;
      },
      // 删除新增开发供应商
      delDlvVendorRow(index) {
        this.tableData.splice(index, 1);
      },
      // 暂存
      saveForm(form, tableData) {
        this.$refs[form].validate((valid) => {
          if (valid) {
            let addDlvVendor = JSON.stringify(tableData);
            this.form.dlvApplyItemJsonStr = addDlvVendor;
            this.axios.post(this.lib.config.host.vendorDlv + '/vendormgt/dlv/dlvApply/save', this.form)
            .then((response) => {
              debugger;
              if (response.data.success){
                this.$message({
                  type: 'success',
                  message: '暂存成功！'
                });
                this.form.id = response.data.resultMap.dlvApplyDto.id;
              } else {
                this.$message({
                  type: 'warning',
                  message: response.data.message
                });
              }
            })
            .catch(function (error) {
              console.log(error);
            });
          }
        })
      },
      // 保存和提交
      saveAndSubmit(form, tableData) {
        this.$refs[form].validate((valid) => {
        if (valid) {
          let addDlvVendor = JSON.stringify(tableData);
          this.form.dlvApplyItemJsonStr = addDlvVendor;
          this.axios.post(this.lib.config.host.vendorDlv + '/vendormgt/dlv/dlvApply/saveAndPublish', this.form)
            .then((response) => {
              if (response.data.success){
                this.$message({
                  type: 'success',
                  message: '提交成功!'
                });
                // 操作成功后跳转页面
                this.$router.push("/Index/VendorDlv/DlvApply");
              } else {
                this.$message({
                  type: 'warning',
                  message: response.data.message
                });
              }
            })
            .catch(function (error) {
              console.log(error);
            });
          }
        })
      },
      // 处理附件上传异常
      handleExceed(files, fileList){
        console.log(files);
        console.log(fileList);
      },
      // 自动上传附件后返回附件url和name
      uploadSuccess: function (response) {
        //附件上传成功回调
        this.form.attFileUrl = response.url;
        this.form.attFileName = response.fileName
      },
      // 格式化供应商等级
      vendorLevelFormatter(row, column){
        if(row.vendorLevel == -1){
          return '淘汰';
        } else if(row.vendorLevel == 1){
          return '注册';
        } else if(row.vendorLevel == 2){
          return '潜在';
        } else {
          return '正式';
        }
      },
      // 格式化引入类型
      applyTypeFormatter(row, column){
        if(column == 1){
          return '新供应商';
        } else {
          return '合格供应商-新物料开发';
        }
      },
      // 开发流程格式化
      dlvItemFlowFormatter(row, column){
        const dlvItemFlows = row.dlvItemFlow.split(',');
        let dlvItemFlowStr = '';
        dlvItemFlows.forEach(function(item){
          if(item === '106301'){
            dlvItemFlowStr += '样品, ';
          } else if(item === '106302'){
            dlvItemFlowStr += '小试, ';
          } else if(item === '106303'){
            dlvItemFlowStr +=  '现场考察, ';
          } else if(item === '106304'){
            dlvItemFlowStr +=  '中试, ';
          } else if(item === '106305') {
            dlvItemFlowStr +=  '批试, ';
          }
        });
        return dlvItemFlowStr;
      },
      // 供货区域格式化
      supplyAreaFormatter(row, column){
        const supplyAreas = row.supplyArea.split(',');
        let supplyAreatStr = '';
          this.supplyAreaOptions.forEach(element =>{
            supplyAreas.forEach(function(item){
              if(item === element.id){
                supplyAreatStr += element.purOrgName + ',';
              }
            });
          })
        return supplyAreatStr;
      }
    }
  }
</script>
<style>
  .upload-file{
    display: flex;
    flex-direction: row-reverse;
    height: 40px;
    width: 340px;
  }

  .upload-file .el-upload-list {
    display: flex;
    flex-direction: row;
    width: calc(100% - 112px);
    border: 1px solid #dcdfe6;
    margin-right: 16px;
    border-radius: 4px;
  }

  .upload-file .el-upload-list li{
    margin-top: 0;
    line-height: 38px;
    vertical-align: middle;
  }

  .upload-file .el-upload-list li .el-icon-close{
    line-height: inherit;
    top:0;
  }
</style>
